package com.zys.background.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zys.background.common.entity.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zys
 * @since 2022-11-21
 */
@Component
public class BgAuthenticationFailureHandler implements AuthenticationFailureHandler {

  @Override
  public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException {
    OAuth2AuthenticationException ex = (OAuth2AuthenticationException) e;

    String errorCode = ex.getError().getErrorCode();

    String msg;
    switch (errorCode) {
      case OAuth2ErrorCodes.INVALID_CLIENT:
        msg = "无效的客户端";
        break;
      case OAuth2ErrorCodes.UNSUPPORTED_GRANT_TYPE:
        msg = "不支持的授权类型";
        break;
      case OAuth2ErrorCodes.INVALID_REQUEST :
      case OAuth2ErrorCodes.UNAUTHORIZED_CLIENT:
        msg = "未授权的客户端";
        break;
      case OAuth2ErrorCodes.INVALID_GRANT:
        msg = "无效的授权";
        break;
      case OAuth2ErrorCodes.INVALID_SCOPE:
        msg = "无效的 scope";
        break;
      default:
        msg = "未知凭证";
        break;
    }

    ObjectMapper mapper = new ObjectMapper();
    res.setStatus(200);
    res.setContentType("application/json");
    res.setCharacterEncoding("utf-8");
    res.getWriter().println(mapper.writeValueAsString(Result.fail(msg)));
  }

}
